<?php

# $Id$
# Copyright 2010, Rasmus Schultz <http://mindplay.dk>

/**
 * FUR acts as a proxy/wrapper class to FURCompiler,
 * which is loaded only when needed.
 */
abstract class FUR
{
  /**
   * Call this method to load generated FUR router class.
   * 
   * @param $fur_path the path to the input (NPS) configuration file.
   * @param $php_path the path to the compiled output PHP class (path must be writable)
   * @param $class_name the name of the generated PHP class.
   */
  public static function load($fur_path, $php_path, $class_name)
  {
    if (class_exists($class_name,false))
      return;
    
    $build = !file_exists($php_path);
    
    if ($build)
      $build = $build && (@filemtime($fur_path) >= @filemtime($php_path));
    
    if ($build)
    {
      $c = self::getCompiler();
      
      file_put_contents(
        $php_path,
        "<?php\n\n" . $c->compile(file_get_contents($fur_path), $class_name)
      );
    }
    
    require $php_path;
  }
  
  /**
   * Load and create FURCompiler.
   */
  public static function getCompiler()
  {
    static $compiler;
    
    if (!isset($compiler))
    {
      require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'FURCompiler.php';
      $compiler = new FURCompiler();
    }
    
    return $compiler;
  }
}

/**
 * FURBase is the base class for a compiled URL manager
 */
abstract class FURBase
{
  /**
   * @var array Map from controller/action to possible route-names
   * Generated router classes override this property.
   */
  public $routeMap=array();
  
  /**
   * Resolve a URI for the given method
   */
  abstract public function resolve($uri, $method);
  
  /**
   * Helper function - maps a given method to an action
   */
  protected function mapAction($actions, $method, $default)
  {
    return isset($actions[$method]) ? $actions[$method] : $default;
  }
}
